package cn.element.io.bio.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ServerReaderThread extends Thread {
    
    private final Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 1.从Socket中获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String l;
            
            while ((l = br.readLine()) != null) {
                // 2.服务端接收到了客户端的消息后,是需要推送给当前所有的在线Socket
                sendMsgToClients(l);
            }
        } catch(Exception e) {
            System.out.println("当前有人下线!");
            
            // 从在线Socket集合中移除本Socket
            Server.socketsOnline.remove(socket);
        }
    }

    /**
     * 把当前客户端发来的消息推送给全部在线的Socket
     */
    private void sendMsgToClients(String msg) throws IOException {
        for (Socket sk : Server.socketsOnline) {
            PrintStream ps = new PrintStream(sk.getOutputStream());
            ps.println(msg);
            ps.flush();
        }    
    }
}
